package com.dartfar.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

public class ExportExcel{
	
	protected final Log log = LogFactory.getLog(ExportExcel.class);

	/***
	 * 
	 * @param 模版名称
	 * @param 数组
	 * @return
	 * @throws IOException
	 */
	
	
	//根据模版生成数据表
	public ByteArrayInputStream WriteToExcelTemplate(String TemplateName, ArrayList fList) throws IOException{
		
		//初始化
		FileInputStream fis = null;
		HSSFWorkbook hwb = null;
		HSSFSheet sheet = null;
		HSSFCellStyle style = null;
		HSSFFont font = null; 
		ArrayList list = null;
		String TempletPath = null;
		
		//获取模版绝对路径
		TempletPath = ServletActionContext.getServletContext().getRealPath("/") + "//template//excel//";
		TempletPath = TempletPath + TemplateName + ".xls";
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
	    //读取模版		
		try {
			fis = new FileInputStream(TempletPath);
		} catch (Exception e) {
			e.printStackTrace();
		}

		//实例化
		hwb = new HSSFWorkbook(fis);
		sheet = hwb.getSheetAt(0);
		style = hwb.createCellStyle();
		font = hwb.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setFont(font);
	    
		//获取最后一行
		int rows = sheet.getLastRowNum() + 1;
	    //遍历数组
	    for(int i = 0; i < fList.size(); i++){
	    	list = (ArrayList) fList.get(i);
	    	//创建行
	    	HSSFRow row = sheet.createRow(rows + i);
	    	for(int j = 0; j < list.size(); j++){
				//创建列
	    		HSSFCell cell = row.createCell(j);
	    		cell.setCellValue(String.valueOf(list.get(j)));
	    	}
	    }
	    
		try {
			hwb.write(baos);
		} catch (Exception e) {
			e.printStackTrace();
		}

		byte[] ba = baos.toByteArray();  
		ByteArrayInputStream bai = new ByteArrayInputStream(ba);
		
		return bai;
	}

	//格式化文件名
	public String FmatFName(String FName){
		try { 
			FName = new String(FName.getBytes("GBK"), "ISO8859-1"); 
			} catch (UnsupportedEncodingException e) { 
				e.printStackTrace(); 
			} 
		return FName;
	}

}
